package com.qf.myshop.service.impl;

import com.qf.myshop.dao.ProductDAO;
import com.qf.myshop.dao.impl.ProductDAOImpl;
import com.qf.myshop.entity.Product;
import com.qf.myshop.service.ProductService;
import com.qf.myshop.utils.Constants;
import com.qf.myshop.utils.JDBCUtils;

import java.sql.SQLException;
import java.util.List;

public class ProductServiceImpl implements ProductService {
    private ProductDAO productDAO = new ProductDAOImpl();

    @Override
    public long count(int ntid) {
        try {
            return productDAO.count(ntid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            try {
                JDBCUtils.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    @Override
    public List<Product> findAll(int ntid, int npage) {
        int skip = (npage - 1) * Constants.PAGE_SIZE;
        try {
            return productDAO.findAll(ntid, skip, Constants.PAGE_SIZE);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                JDBCUtils.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public Product findById(int npid) {
        try {
            return productDAO.findById(npid);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                JDBCUtils.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(new ProductServiceImpl().count(1));
        System.out.println(new ProductServiceImpl().findAll(1, 1));
    }
}
